# -*- coding: utf-8 -*-
"""v1_0_2

- change rectangle, polygon and ocr_polygon coords from center origin to upper left origin

Revision ID: a53874071f6e
Revises: e660f34b820d
Create Date: 2023-02-08 23:23:59.709127

"""
from alembic import op
import sqlalchemy as sa

from paddlelabel.api.model import Annotation, Data
from paddlelabel.config import se


# revision identifiers, used by Alembic.
revision = "a53874071f6e"
down_revision = "e660f34b820d"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###

    rects = Annotation._get(type="rectangle", many=True)
    for rect in rects:
        data = Data._get(data_id=rect.data_id)
        assert data.size is not None and len(data.size) != 0, f"Data size is missing for data_id {data.data_id}"
        h, w = map(int, data.size.split(",")[1:])
        res = list(map(float, rect.result.split(",")))
        res[0] += w / 2
        res[1] += h / 2
        res[2] += w / 2
        res[3] += h / 2
        rect.result = ",".join(map(lambda v: str(int(v)), res))

    polygons = Annotation._get(type="polygon", many=True)
    for polygon in polygons:
        data = Data._get(data_id=polygon.data_id)
        assert data.size is not None and len(data.size) != 0, f"Data size is missing for data_id {data.data_id}"
        h, w = map(int, data.size.split(",")[1:])
        res = list(map(float, polygon.result.split(",")))
        for idx in range(0, len(res), 2):
            res[idx] += w / 2
        for idx in range(1, len(res), 2):
            res[idx] += h / 2
        polygon.result = ",".join(map(lambda v: str(int(v)), res))

    ocr_polygons = Annotation._get(type="ocr_polygon", many=True)
    for ocr_polygon in ocr_polygons:
        data = Data._get(data_id=ocr_polygon.data_id)
        assert data.size is not None and len(data.size) != 0, f"Data size is missing for data_id {data.data_id}"
        h, w = map(int, data.size.split(",")[1:])
        res = ocr_polygon.result.split("|")
        point_stops = res.index("")
        for idx in range(point_stops):
            res[idx] = float(res[idx])
        for idx in range(0, point_stops, 2):
            res[idx] += w / 2
        for idx in range(1, point_stops, 2):
            res[idx] += h / 2
        for idx in range(point_stops):
            res[idx] = str(int(res[idx]))
        ocr_polygon.result = "|".join(res)

    se.commit()

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###
